package com.mxw.commons.restful;

import cn.hutool.core.text.CharSequenceUtil;
import com.mxw.commons.errorcode.IErrorCode;
import com.mxw.commons.exception.CustomException;
import lombok.Data;

import java.io.Serializable;

@Data
public class Result<T> implements Serializable {
  private static final String DEFAULT_CODE = "00000000";
  private static final String DEFAULT_MSG = "操作成功";
  private String code;
  private String msg;
  private T data;

  public static <T> Result<T> respondWithIErrorCode(IErrorCode errorCode) {
    return respond(
        errorCode.getCodeId(),
        CharSequenceUtil.isBlank(errorCode.getMsg()) ? errorCode.getCodeName() : errorCode.getMsg(),
        null);
  }

  public static <T> Result<T> respondWithIErrorCode(IErrorCode errorCode, String msg) {
    return respond(errorCode.getCodeId(), msg, null);
  }

  public static <T> Result<T> respondWithCustomException(CustomException exception) {
    return respond(exception.getCodeId(), exception.getMessage(), null);
  }

  public static <T> Result<T> respond(T data) {
    return respond(DEFAULT_CODE, DEFAULT_MSG, data);
  }

  public static <T> Result<T> respond() {
    return respond(DEFAULT_CODE, DEFAULT_MSG, null);
  }

  public static <T> Result<T> respond(String code, String msg, T data) {
    Result<T> r = new Result<>();
    r.setCode(code);
    r.setMsg(msg);
    r.setData(data);
    return r;
  }
}
